package com.BookManage;

public class SequenceList<T> {
    final int defaultSize=5;
    private T[]books;
    private int length;

    /**
     * 建造一个无参构造
     */
    public SequenceList() {
        length=0;
        books=(T[]) new Object[defaultSize];
    }

    /**
     * 建造一个有参构造
     * @param n
     */
    public SequenceList(int n){
        if(n<=0){
            System.out.println("你的集合长度不能小于或等于零");
            System.exit(1);
        }
        length=0;
        books=(T[]) new Object[n];

    }

    /**
     * 顺序表的查询
     * @param index
     * @return
     */

    public  T searchBook(int index) {
        if (isEmpty()){
            System.out.println("序列表为空");
            return null;
        }
        if (index<1||index>length){
            return null;
        }
        return books[index-1];
    }

    /**
     * 顺序表的更改
     * @param obj
     * @param index
     * @return
     */
    public   boolean updateBook(T obj,int index) {
        if (isEmpty()){
            return false;
        }
        if (index<1||index>length){
            return false;
        }
        books[index-1]=obj;
        return true;
    }

    /**
     * 判断顺序表是否为空
     * @return
     */
    private boolean isEmpty(){
        return length==0;
    }

    /**
     * 存储图书信息
     * @param book
     * @return
     */
    public  boolean SaveBook(T book){
        if (length==books.length){
            T[]temp= (T[]) new Object[length*2];
            System.arraycopy(books, 0, temp, 0, books.length);
            books=temp;
        }
        for (int i = 0; i < books.length; i++) {
            if (books[i]==null){
                books[i] = book;
                length++;
                return true;
            }
        }
        return false;
    }

    /**
     * 插入书本信息
     * @param book
     * @param index
     * @return
     */
    public  boolean InsertBook(T book,int index){
        if (index<1||index> books.length+1){
            System.out.println("值不合法");
            return false;
        }
        if (length==books.length){
            T[]temp= (T[]) new Object[length*2];
            System.arraycopy(books, 0, temp, 0, books.length);
            books=temp;
        }
        for (int i = length; i >=index ; i--) {
            books[i]=books[i-1];
        }
        books[index-1]=book;
        return true;
    }
    public void getAll(){
        System.out.print("["+" ");
        for (T book : books) {
            if (book != null) {
                System.out.print(book);
            }
        }
        System.out.print(" "+"]");
    }
    public  boolean DeleteBook(Book book) {
        if (isEmpty()){
            System.out.println("顺序表内容为空");
            return false;
        }
        return false;
    }

    public int size(){
        return length;
    }

}


